// ignore: library_prefixes
import 'dart:convert';

import 'dart:io';

import 'package:crypto/crypto.dart';
import 'package:web_socket_channel/io.dart';

class AudioTextUtil {
  static AudioTextUtil get instance => AudioTextUtil();
  static AudioTextUtil? _instance;
  factory AudioTextUtil() {
    _instance ??= AudioTextUtil._();
    return _instance!;
  }
  static const appid = '6033af33';
  static const secredid = '77d98357674695b9955a682ac882524a';
  static const appkey = 'da207487990167eb545e86bc05f14451';

  IOWebSocketChannel? ioChannel;
  bool isConnected = false;
  AudioTextUtil._() {
    init();
  }

  String getSigna(String str) {
    var content = utf8.encode(str);
    var _md = md5.convert(content);

    var _hmac = Hmac(sha256, utf8.encode(secredid));
    var _sha = _hmac.convert(utf8.encode(_md.toString()));
    var digest = base64Encode(_sha.bytes);
    return digest;
  }

  init() {}

  void connect() {
    var date = DateTime.now();

    var ts = HttpDate.format(date);
    // ts = 'Wed, 10 Jul 2019 07:35:43 GMT';
    var _host = 'iat-api.xfyun.cn';
    var _rLine = 'GET /v2/iat HTTP/1.1';
    var _signatureOriginal = 'host: $_host\ndate: $ts\n$_rLine';
    var _hmac = Hmac(sha256, utf8.encode(secredid));
    var _sha = _hmac.convert(utf8.encode(_signatureOriginal));

    var _signature = base64Encode(_sha.bytes);

    var _authorization =
        '''api_key="$appkey", algorithm="hmac-sha256", headers="host date request-line", signature="$_signature"''';

    var authorization = base64Encode(utf8.encode(_authorization));

    var _urlStr =
        'wss://iat-api.xfyun.cn/v2/iat?authorization=$authorization&date=$ts&host=$_host';

    ioChannel = IOWebSocketChannel.connect(
      Uri.parse(_urlStr),
      pingInterval: const Duration(seconds: 3),
    );

    ioChannel?.sink.add(base64Encode(utf8.encode('ping')));
    ioChannel?.stream.listen(
      (message) {
        ioChannel?.sink.add('received!');
        print(message);
        isConnected = true;
      },
      onError: (e) {
        print(e);
      },
      onDone: () {
        print('onDone');
      },
    );
  }

  void sendAudio() {
    if (ioChannel?.closeCode != null) {
      connect();
      return;
    }
    var _parm = {
      "common": {
        // 公共请求参数
        "app_id": "123456"
      },
      "business": {"language": "zh_cn", "domain": "iat", "accent": "mandarin"},
      "data": {
        "status": 0,
        "format": "audio/L16;rate=16000",
        "encoding": "raw",
        "audio": "exSI6ICJlbiIsCgkgICAgInBvc2l0aW9uIjogImZhbHNlIgoJf..."
      }
    };
    var _encodeParm = base64Encode(utf8.encode(jsonEncode(_parm)));
    ioChannel?.sink.add(_encodeParm);
  }

  void close() {
    ioChannel?.sink.close();
  }
}
